/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.alpha.parse;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.CompositeTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.htmlparser.util.SimpleNodeIterator;


/**
 *
 * @author alvar
 */
public class D6TopicListParser implements TopicListParser{
    protected  StringBuilder url;
    protected String blockName;
    protected Map<Integer,String> topicList;
    protected List numOfReply;
    protected Parser p;
    protected int page;
    
    public D6TopicListParser(String url, int fid){
        this(url,fid,1);
    }
    
    public D6TopicListParser(String url, int fid, int page){
        this.page = page;
        this.url = new StringBuilder(url)
                .append("?fid-")
                .append(fid)
                .append("-page-")
                .append(page)
                .append(".html/");
        try {
            
            blockName = new Parser(url).parse(new TagNameFilter("a")).elementAt(1).toPlainTextString();
            processParse();
        } catch (ParserException ex) {
            Logger.getLogger(D6TopicListParser.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public int getPageNum(){
        return page;
    }
    
    public List getNumOfReply(){
        return numOfReply;
    }
    
    public Map getTopicList(){
        return topicList;
    }
    
    public void refresh() throws ParserException{
        processParse();
        System.gc();
    }

    private void processParse() throws ParserException {
        numOfReply = new ArrayList<String>();
        topicList = new LinkedHashMap<Integer, String>();
        p = new Parser(url.toString());
        Node[] list;
        Pattern fidPattern;
        Pattern numPattern; 
        Matcher matcher;
        p = new Parser(url.toString());
        list = p.parse(new TagNameFilter("li")).toNodeArray();
        for(int i = 0;i<list.length; i++){
            String line = list[i].toHtml();
            fidPattern = Pattern.compile("\\d{8,}+");
            
            matcher = fidPattern.matcher(line);
            while(matcher.find()){
                topicList.put(Integer.parseInt(matcher.group()), list[i].getChildren().elementAt(0).toPlainTextString());
//                System.out.println(list[i].getChildren().elementAt(3).toHtml());
                numOfReply.add(list[i].getChildren().elementAt(3).toPlainTextString());
            }
        }
    }
    
    
}
